package com.qianfeng.smartdevices.service.impl;


import com.qianfeng.smartdevices.cache.MenuCache;
import com.qianfeng.smartdevices.dto.ResultCode;
import com.qianfeng.smartdevices.event.MenuChangeEvent;
import com.qianfeng.smartdevices.exceptions.AddErrorException;
import com.qianfeng.smartdevices.mapper.MenusMapper;
import com.qianfeng.smartdevices.pojo.BaseUser;
import com.qianfeng.smartdevices.pojo.CheckStatus;
import com.qianfeng.smartdevices.pojo.Menu;
import com.qianfeng.smartdevices.pojo.Role;
import com.qianfeng.smartdevices.service.MenusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;


@Service
@Transactional
public class MenusServiceImpl implements MenusService {

    private MenusMapper menusMapper;
    private MenuCache menuCache;
    private ApplicationContext context;
    @Autowired
    public void setMenuCache(MenuCache menuCache) {
        this.menuCache = menuCache;
    }
    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

    @Autowired
    public void setMenusMapper(MenusMapper menusMapper) {
        this.menusMapper = menusMapper;
    }

    @Override
    public List<Menu> findAllMenus() {
        return menusMapper.findAllMenus();
    }

    @Override
    public List<Menu> findMenuByRoleId(Long rid) {
        return menusMapper.findMenuByRoleId(rid);
    }

    @Override
    public List<Menu> findALlLeftMenus() {
        BaseUser baseUser = (BaseUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        List<Role> roleList = baseUser.getRoleList();
        ArrayList<Menu> userMenu = new ArrayList<>();
        roleList.forEach(role -> {
            userMenu.addAll(role.getMenuList().stream().filter(menu -> {
                return menu.getType() == 1L;
            }).collect(Collectors.toList()));
        });
        return userMenu;

    }

    @Override
    public void addMenu(Menu menu) {
        if (menu.isNull(CheckStatus.ADD)){
            throw new AddErrorException("数据传输错误", ResultCode.DATA_NOT_ALLOW_NUL);
        }
        menusMapper.addMenu(menu);
        context.publishEvent(new MenuChangeEvent());
    }

    @Override
    public void updateMenu(Menu menu) {
        if (menu.isNull(CheckStatus.UPDATE)){
            throw new AddErrorException("数据不能为空", ResultCode.DATA_NOT_ALLOW_NUL);
        }
        menusMapper.updateMenu(menu);
        context.publishEvent(new MenuChangeEvent());
    }
}
